# encoding: utf-8

require 'gd2-ffij'
require 'rqrcode'

module GenQR

  class QR
    attr_accessor :png

    def initialize( string, *args )
      options      = args.extract_options!
      pix_size     = options[:size] || 6
      dark_color   = options[:dark] || 0x000000
      bright_color = options[:bright] || 0xffffff

      qr = RQRCode::QRCode.new string, level: :l, size: 4
      size = qr.module_count * pix_size

      image = GD2::Image::IndexedColor.new size, size
      dark   = GD2::Color.new_from_rgba dark_color
      bright = GD2::Color.new_from_rgba bright_color
      image.palette << bright
      image.palette << dark
      image.draw do |canvas|
        qr.modules.each_index do |y|
          qr.modules.each_index do |x|
            canvas.color = qr.is_dark(y, x) ? dark : bright
            canvas.rectangle(x * pix_size,
                             y * pix_size,
                       (x + 1) * pix_size,
                       (y + 1) * pix_size, true)
          end
        end
      end
      self.png = image.png
    end
  end
end

include GenQR
